package edu.chen.bean;

import javax.persistence.*;
import java.util.Set;

@Entity
@Table(name = "product_")
public class Product {
    private int id;
    private String name;
    private Double price;
    private Category category;
    private Set<User> users;

    public Product(){}

    public Product(String name, Double price) {
        this.name = name;
        this.price = price;
    }

    /**
     * //@ManyToMany    该注解表明多对多的关系
     * //@JoinTable     JoinTable是在维护第三章表时使用的,由JoinTable标注表明该表的操作会影响到第三张表格
     * name 第三章表名
     * joinColumns  表示本表格外键
     * inverseJoinColumns   表示对方表格外键
     */
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "product_user",
            joinColumns = {@JoinColumn(name = "pid")},
            inverseJoinColumns = {@JoinColumn(name = "uid")})
    public Set<User> getUsers() {
        return users;
    }

    public void setUsers(Set<User> users) {
        this.users = users;
    }

    //乐观锁添加
//    private int version = 1;

    /**
     *  //@ManyToOne    指定多对一的关系映射
     *  fetch表示加载模式,由FetchType保存,LAZY为延迟加载
     *  //@JoinColumn
     *  name 指定外键
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cid")
    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }


    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Basic
    @Column(name = "price")
    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Product product = (Product) o;

        if (id != product.id) return false;
        if (name != null ? !name.equals(product.name) : product.name != null) return false;
        if (price != null ? !price.equals(product.price) : product.price != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (price != null ? price.hashCode() : 0);
        return result;
    }
}
